//
//  PersistenceData.m
//  YueMi
//
//  Created by Rainbow on 4/27/11.
//  Copyright 2011 iTotemStudio. All rights reserved.
//

#import "PersistenceData.h"
#import "CacheData.h"

#define IBT_LISTENING_WORDS  @"IBT_LISTENING_WORDS";

#define UPDATE_TIMESTAMP        @"UPDATE_TIMESTAMP"
#define AD_UPDATE_TIMESTAMP     @"AD_UPDATE_TIMESTAMP"
#define SAVED_ADVERTISINGS      @"SAVED_ADVERTISINGS"
#define AD_UPDATE_COUNT         @"AD_UPDATE_COUNT"
#define WORD_UPDATE_TIMESTAMP(category) [NSString stringWithFormat:@"WORD_UPDATE_TIMESTAMP_%@",category]

@implementation PersistenceData

static PersistenceData *_sharedInst;

+(PersistenceData *)sharedData
{
	@synchronized(self)
	{
		if (_sharedInst == nil) {
			_sharedInst = [[PersistenceData alloc] init];
		}
	}
	return _sharedInst;
}	


- (Letter *)getLetterByName:(NSString *)letterName
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    if (wordData == nil) {
        return nil;
    }
	NSMutableDictionary *words = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
	if (words != nil) {
        return [words objectForKey:letterName];
	}
    return nil; 
}

- (NSMutableDictionary *)getSavedLetters
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    if (wordData == nil) {
        return nil;
    }
	NSMutableDictionary *words = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
	if (words != nil) {
        return words;
	}
    return nil; 
}

- (void)addLetter:(Letter *)letter category:(NSString *)category
{
    if (![category isEqualToString:[CacheData sharedData].currentCategory]) {
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    if (wordData == nil) {
        NSMutableDictionary *wordsDic = [[[NSMutableDictionary alloc] init] autorelease];
        [wordsDic setObject:letter forKey:letter.letter];
        [CacheData sharedData].savedLetters = wordsDic;
        wordData = [NSKeyedArchiver archivedDataWithRootObject:wordsDic];
    }
    else
    {
        NSMutableDictionary *wordsDic = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
        for (NSString *enumletter in [wordsDic allKeys]) {
            if ([letter.letter isEqualToString:enumletter]) {
                if ([CacheData sharedData].selectedLetter && [[CacheData sharedData].selectedLetter.letter isEqualToString:letter.letter]) {
                    [letter syncLetterStauts:[CacheData sharedData].selectedLetter];
                }else{
                    Letter *existLetter = [wordsDic objectForKey:enumletter];
                    [letter syncLetterStauts:existLetter];
                }
                break;
            }
        }
        [wordsDic setObject:letter forKey:letter.letter];
        if ([CacheData sharedData].selectedLetter) {
            if (![[CacheData sharedData].selectedLetter.letter isEqualToString:letter.letter]) {
                [wordsDic setObject:[CacheData sharedData].selectedLetter forKey:[CacheData sharedData].selectedLetter.letter];
            }
            else{
                [CacheData sharedData].selectedLetter = letter;
            }
        }
        [CacheData sharedData].savedLetters = wordsDic;
        wordData = [NSKeyedArchiver archivedDataWithRootObject:wordsDic];
    }
    [defaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:WORD_UPDATE_TIMESTAMP(category)];
    [defaults setObject:wordData forKey:[CacheData sharedData].currentCategory];
    [defaults synchronize];
}

- (void)syncWordsStatus:(NSMutableArray *)words withLetter:(NSString *)letter
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    NSMutableDictionary *wordsDic = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
    [wordsDic setObject:words forKey:letter];
    wordData = [NSKeyedArchiver archivedDataWithRootObject:wordsDic];
    [defaults setObject:wordData forKey:[CacheData sharedData].currentCategory];
    [defaults synchronize];
}

- (void)syncLetterStatus:(Letter *)letter
{
    if (letter == nil) {
        return;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    NSMutableDictionary *wordsDic = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
    [wordsDic setObject:letter forKey:letter.letter];
    wordData = [NSKeyedArchiver archivedDataWithRootObject:wordsDic];
    [defaults setObject:wordData forKey:[CacheData sharedData].currentCategory];
    [defaults synchronize];
}


- (BOOL)haveLetter:(NSString *)letterName
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSData *wordData = [defaults objectForKey:[CacheData sharedData].currentCategory];
    if (wordData == nil) {
        return NO;
    }
	NSMutableDictionary *words = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
	if ([words objectForKey:letterName]) {
        return YES;
	}
    return NO; 
}

- (NSMutableArray *)getWrongWords
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSData *wordData = [defaults objectForKey:[[CacheData sharedData].currentCategory stringByAppendingString:@"_WRONG"]];
    if (wordData == nil) {
        return nil;
    }
	NSMutableArray *words = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:wordData];
	if (words != nil) {
        return words;
	}
    return nil; 
}

- (void)syncWrongWords:(NSMutableArray *)wrongWords;
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *wordData = [NSKeyedArchiver archivedDataWithRootObject:wrongWords];
    [defaults setObject:wordData forKey:[[CacheData sharedData].currentCategory stringByAppendingString:@"_WRONG"]];
    [defaults synchronize];
}

- (NSString *)getUpdateTimestamp
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSTimeInterval timestamp = [defaults doubleForKey:UPDATE_TIMESTAMP];
    return [NSString stringWithFormat:@"%f",timestamp];
}

- (void)setUpdateTimestamp:(NSTimeInterval)timestamp
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setDouble:timestamp forKey:UPDATE_TIMESTAMP];
}

- (NSString *)getAdUpdateTimestamp
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSTimeInterval timestamp = [defaults doubleForKey:AD_UPDATE_TIMESTAMP];
    return [NSString stringWithFormat:@"%f",timestamp];
}

- (void)setAdUpdateTimestamp:(NSTimeInterval)timestamp
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setDouble:timestamp forKey:AD_UPDATE_TIMESTAMP];
}

- (NSString *)getAdUpdateCount
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSInteger count = [defaults integerForKey:AD_UPDATE_COUNT];
    return [NSString stringWithFormat:@"%d",count];
}

- (void)setAdUpdateCount:(NSInteger)count
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:count forKey:AD_UPDATE_COUNT];
}

- (void)setAdvertisings:(NSArray *)advertisings
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *advertisingsData = [NSKeyedArchiver archivedDataWithRootObject:advertisings];
    [defaults setObject:advertisingsData forKey:SAVED_ADVERTISINGS];
    [defaults synchronize];
}

- (NSArray *)getAdvertsings
{
    [self setAdUpdateCount:0];
    [self setAdUpdateTimestamp:[[NSDate date] timeIntervalSince1970]];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSData *advertisingsData = [defaults objectForKey:SAVED_ADVERTISINGS];
    if (advertisingsData == nil) {
        return nil;
    }
	NSArray *advertisings = (NSArray *)[NSKeyedUnarchiver unarchiveObjectWithData:advertisingsData];
	if (advertisings != nil) {
        return advertisings;
	}
    return nil; 
}

- (NSTimeInterval)getTimestampByCategory:(NSString *)category
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults doubleForKey:WORD_UPDATE_TIMESTAMP(category)];
}

@end
